package cn.acewill.yxd.yunxundian.ui.sign;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.SignUpInfo;
import cn.acewill.yxd.yunxundian.pubClass.AsynData;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.TopDialogUtils;
import cn.acewill.yxd.yunxundian.utils.baiduUtils.BaiduMapUtils;

/**
 * Created by AAA on 2017/4/19.
 */

public class SignInActivity extends BaseActivity implements View.OnClickListener {

    private LatLng MyPosition, shopPosition;
    private BaiduMap mBaiduMap;
    private boolean isFirstLoc = true;
    private boolean isMyfirst=true;
    private String shopName;
    private Button signIn;
    private Dialog dialog;
    private int isinrange;
    private int isneedupdateshopXY = 1;
    private String signTime;
    protected YXDAPP yxdapp = new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    protected Context mcontext;
    public static int shopId;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener;
    private int rrschid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTitleBar("签到签出");
        setContentView(R.layout.sign_map);
        super.onCreate(savedInstanceState);
        mcontext = this;
        initView();
        //OnLocation();
        markShop();
    }

    public void initView() {
        PackageManager pm = getPackageManager();
        boolean permission = (PackageManager.PERMISSION_GRANTED ==
                pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", "cn.acewill.yxd.yunxundian"));
        boolean permission1 = (PackageManager.PERMISSION_GRANTED ==
                pm.checkPermission("android.permission.ACCESS_COARSE_LOCATION", "cn.acewill.yxd.yunxundian"));
        if(!permission || !permission1)
        {
            showAnimaDialog(SignInActivity.this,"请开启系统定位服务");
            finish();
        }

        rrschid = getIntent().getIntExtra("schid",-1);
        MapView myMap = (MapView) findViewById(R.id.myMap);
        TextView moreBtn = (TextView) findViewById(R.id.MoreBtn);
        moreBtn.setOnClickListener(this);
        this.signIn = (Button) findViewById(R.id.signIn);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.cricle_run);
        signIn.setAnimation(animation);
        signIn.setOnClickListener(this);

        mBaiduMap = myMap.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        //创建用于定位的客户端对象

        mLocationClient = new LocationClient(getApplicationContext());
        initLocation();
        //声明LocationClient类
        mLocationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                MyLocationData myLocationData = new MyLocationData.Builder()
                        .accuracy(bdLocation.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(100).latitude(bdLocation.getLatitude())
                        .longitude(bdLocation.getLongitude()).build();
                mBaiduMap.setMyLocationData(myLocationData);
                MyPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                if(isMyfirst)
                {
                    MapStatusUpdate mapStatus = MapStatusUpdateFactory.newLatLngZoom(new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude()), 18);
                    mBaiduMap.setMapStatus(mapStatus);
                    isMyfirst=false;
                }
            }

            @Override
            public void onConnectHotSpotMessage(String s, int i) {

            }
        });
        mLocationClient.start();

        shopId = getIntent().getIntExtra("shopId", -1);
        shopName = getIntent().getStringExtra("shopName");
        double ycol = getIntent().getDoubleExtra("ycol", 0);
        double xcol = getIntent().getDoubleExtra("xcol", 0);
        if(MainActivity.signId>0) {
                try {
                    sui = db.selector(SignUpInfo.class).where("_ID", "=", MainActivity.signId + "").findFirst();
                    if(sui!=null)
                        shopId=sui.getShopId();
                } catch (DbException e) {
                    e.printStackTrace();
                }
        }
        if(MainActivity.signId>0)
            signIn.setText("签出");
        else
            signIn.setText("签到");
        shopPosition = new LatLng(ycol, xcol);
    }

    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span=30000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(false);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(false);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(false);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(true);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);
    }

    public void OnLocation() {
        BaiduMapUtils.getInstance(this).getLocate(new BaiduMapUtils.OnLocationMapListener() {
            @Override
            public void getCurrLocation(BDLocation location) throws DbException {
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(100).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                MyPosition = new LatLng(location.getLatitude(), location.getLongitude());

                if (isFirstLoc) {
                    isFirstLoc = false;
                    LatLng ll = new LatLng(location.getLatitude(),
                            location.getLongitude());
                    if((int)location.getAltitude()==0) {
                        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                            if (ActivityCompat.checkSelfPermission(SignInActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(SignInActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location1 != null) {
                                double[] latlng = (pubClass.wgs2bd(location1.getLatitude(), location1.getLongitude()));
                                ll = new LatLng(latlng[0], latlng[1]);
                                MyPosition = new LatLng(latlng[0], latlng[1]);
                                locData = new MyLocationData.Builder()
                                        .accuracy(location.getRadius())
                                        // 此处设置开发者获取到的方向信息，顺时针0-360
                                        .direction(100).latitude(latlng[0])
                                        .longitude(latlng[1]).build();
                            }

                        }
                    }
                    mBaiduMap.setMyLocationData(locData);
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(ll).zoom(18.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(MyPosition));
                }
            }
        });

    }



    //将门店标记在地图上
    public void markShop(){
        BitmapDescriptor bitmap= BitmapDescriptorFactory.fromResource(R.mipmap.icon_location);
        OverlayOptions options=new MarkerOptions().position(shopPosition).icon(bitmap).title(shopName);
        mBaiduMap.addOverlay(options);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.MoreBtn:
                showDialog2();
                break;
            case R.id.signIn:
                if(MainActivity.signId==0) {
                    //再次定位，获取最新坐标
                    OnLocation();
                    if (shopPosition.longitude == 0 || shopPosition.latitude == 0) {
                        dialog = new Dialog(this);
                        View view = LayoutInflater.from(this).inflate(R.layout.sign_setshopxy_dialog, (ViewGroup) getWindow().getDecorView(),false);
                        TextView setShopCol = (TextView) view.findViewById(R.id.setShopCol);
                        setShopCol.setOnClickListener(this);
                        TextView btnCanel = (TextView) view.findViewById(R.id.btnCanel);
                        btnCanel.setOnClickListener(this);
                        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        dialog.setContentView(view);
                        dialog.show();
                    } else {

                        showDialog();
                    }
                }
                else{
                    signout();
                }
                break;
            //签到
            case R.id.doSign:
                dialog.dismiss();
                getCurrentTime();
                SignInfo();
                break;
            case R.id.cancel_action:
                dialog.dismiss();
                break;
            //设置门店坐标
            case R.id.setShopCol:
                dialog.dismiss();
                isneedupdateshopXY=0;
                getCurrentTime();
                //未定位完成

                if (MyPosition==null||(MyPosition.longitude!=0&&MyPosition.latitude!=0)){
                    showAnimaDialog(this,"正在定位，请稍后");
                    return;
                }
                SignInfo();

                break;
            /*门店坐标为空的的签到*/
            case R.id.btnCanel:
                isneedupdateshopXY=1;
                dialog.dismiss();

                break;
            //更多弹出框
            case R.id.closeDialog:
                dialog.dismiss();
                break;
            case R.id.signOut:
                Intent in =new Intent(this,HistoryEvaluationActivity.class);
                in.putExtra("shopid",shopId);
                startActivity(in);
                dialog.dismiss();
                break;
            case R.id.myTask:
                // TODO: 2018/2/7 门店签到的逻辑 
               // Intent intent=new Intent(this,EvaluationMianActivity.class);
                Intent intent = new Intent(this,MyEvaluationActivity.class);
                intent.putExtra("loadfrom",0);
                intent.putExtra("shopid",shopId);
                startActivity(intent);
                dialog.dismiss();
                break;
        }

    }

    protected SignUpInfo sui;

    public void signout()
    {
        try {
            sui = db.selector(SignUpInfo.class).where("_ID", "=", MainActivity.signId + "").findFirst();
            if(sui!=null) {
                sui.setOutTime(BaseActivity.getNowDate());
                Map<String,Object> map=new HashMap<>();
                map.put("task","signoutsync");
                map.put("siJson", JSON.toJSONString(sui));
                pubClass.Post(this,pubClass.Server_namehzm,map,new pubClass.MyCallBack<String>(){
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        String[] array=result.split("\\|");
                        if(array[0].equals("200")) {
                            try {
                                db.saveOrUpdate(sui);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                            showAnimaDialog(SignInActivity.this,"签出成功");
                            MainActivity.signId=0;
                            changeType();
                            finish();
                        }
                        else
                        {
                            showAnimaDialog(SignInActivity.this,"签出失败，参数错误");
                        }
                    }
                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        try {
                            db.saveOrUpdate(sui);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        showAnimaDialog(SignInActivity.this,"签出成功");
                        MainActivity.signId=0;
                        changeType();
                        finish();
                    }

                });

            }
        }catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void SignInfo(){
        Map<String,Object> map=new HashMap<>();
        map.put("task","signUpEmployee");
        map.put("empid", MainActivity.id);
        map.put("shopid",shopId);
        map.put("lat",""+MyPosition.latitude);
        map.put("lng",""+MyPosition.longitude);
        map.put("isinrange",isinrange);//0 小于1000m，1大于1000m
        map.put("isneedupdateshopXY",isneedupdateshopXY);//0设置坐标，1门店无坐标
        map.put("checkTime",signTime);

        final SignUpInfo nsi=new SignUpInfo();
        nsi.setEmpId(MainActivity.id);
        nsi.setIsInRange(isinrange);
        nsi.setInTime(signTime);
        nsi.setShopId(shopId);
        nsi.setXCol(MyPosition.longitude);
        nsi.setYCol(MyPosition.latitude);
        try{
            db.saveOrUpdate(nsi);
            MainActivity.signId=nsi.get_ID();
        } catch (DbException e) {
            e.printStackTrace();
        }

        pubClass.Post(this,pubClass.Server_namehzm,map,new pubClass.MyCallBack<String>(){
            public void onSuccess(String result) {
                super.onSuccess(result);
                String[] strings = result.split("\\|");
                if (strings[0].equals("201")) {
                    showAnimaDialog(SignInActivity.this,strings[1]);
                }
                else if (strings[0].equals("200")) {
                    showAnimaDialog(SignInActivity.this,"签到成功");
                    AsynData data=new AsynData(null);
                    try {
                        data.asynSignUpData(MainActivity.id);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //如果日程id不为-1就就执行任务
                    if (rrschid!=-1){
//                        Intent in = new Intent(mcontext,WrittingEvaluationListActivity.class);
//                        in.putExtra("rrschid",rrschid);
//                        startActivity(in);
                        finish();
                    }else{
                        //Intent in=new Intent(mcontext,EvaluationMianActivity.class);
                        Intent in = new Intent(mcontext,MyEvaluationActivity.class);
                        in.putExtra("loadfrom",0);
                        in.putExtra("shopid",shopId);
                        changeType();
                        startActivity(in);
                    }
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                //离线情况
                    showAnimaDialog(SignInActivity.this,"签到成功");
                    changeType();
                if (rrschid!=-1) {
//                    Intent in = new Intent(mcontext, WrittingEvaluationListActivity.class);
//                    in.putExtra("rrschid", rrschid);
//                    startActivity(in);
                    finish();
                }else{
             //       Intent in=new Intent(mcontext,EvaluationMianActivity.class);
                    Intent in = new Intent(mcontext,MyEvaluationActivity.class);
                    in.putExtra("loadfrom",0);

                    in.putExtra("shopid",shopId);
                    startActivity(in);
                }
            }

        });
    }


    public void changeType()
    {
        if(MainActivity.signId>0) {
            signIn.setText("签出");
        }
        else
        {
            signIn.setText("签到");
        }
    }

    public void showDialog(){
        Log.e("MyPosition",MyPosition+"");
        double Redistance=DistanceUtil.getDistance(MyPosition,shopPosition);
        //如果转化失败会返回-1，防止点击进入
        if (Redistance==-1){
            BaseActivity.showAnimaDialog(this,"正在定位，请稍后");
            return;
        }
        if(Redistance>=1000) {
            isinrange = 0;
        }else {
            isinrange = 1;
        }
        dialog=new Dialog(this);
        View view= LayoutInflater.from(this).inflate(R.layout.sign_dialog, (ViewGroup) getWindow().getDecorView(),false);
        TextView countText= (TextView) view.findViewById(R.id.countText);
        TextView doSign= (TextView) view.findViewById(R.id.doSign);
        doSign.setOnClickListener(this);
        TextView cancel_action= (TextView) view.findViewById(R.id.cancel_action);
        cancel_action.setOnClickListener(this);

        if (Redistance>=1000){
            double dd=Redistance/1000;
            double distance=Math.round(dd*10)/10.0;
            countText.setText(distance+"千米");
        }else{
            double distance=Math.round(Redistance*10)/10.0;
            countText.setText(distance+"米");
        }
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(view);
        dialog.show();
    }

    public void showDialog2(){
        dialog=new Dialog(this,R.style.BottomDialog);
        View view= LayoutInflater.from(this).inflate(R.layout.map_more_dialog, (ViewGroup) getWindow().getDecorView(),false);
        TopDialogUtils.showTopDialog(this,dialog,view,3);
        Button closedialog= (Button) view.findViewById(R.id.closeDialog);
        closedialog.setOnClickListener(this);
        TextView signOut= (TextView) view.findViewById(R.id.signOut);
        signOut.setOnClickListener(this);
        TextView myTask= (TextView) view.findViewById(R.id.myTask);
        myTask.setOnClickListener(this);
        dialog.show();
    }

    public void getCurrentTime(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date date=new Date(System.currentTimeMillis());
        signTime=formatter.format(date);
    }

    public void LocalSign() throws DbException {

        SignUpInfo bean=db.selector(SignUpInfo.class).where("ID","=",MainActivity.id).findFirst();
        bean.setIsInRange(isinrange);
        bean.setTimeCreated(signTime);
        if(isneedupdateshopXY==0){
            bean.setXCol(MyPosition.latitude);
            bean.setYCol(MyPosition.longitude);
        }
        db.saveOrUpdate(bean);

    }
}


